package com.jzl.swing.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jzl.swing.rowmapper.RowMapper;



public final class JDBCTemplate {
	public static int executeUpdate(String sql, Object... param) throws SQLException {
		int rows = -1;
		Connection connection = JDBCUtil.getConnecion();
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		if (null != param && param.length > 0) {
			for(int i = 0; i < param.length; i++) {
				preparedStatement.setObject((i+1), param[i]);
				
			}
		}
		rows = preparedStatement.executeUpdate();
		close(null, preparedStatement);
		
		return rows;
	}
	
	
	public static List<Object> executeQuery(String sql, RowMapper rowMapper, Object...param) throws SQLException {
		List<Object> list = new ArrayList<Object>();
		Connection connection = JDBCUtil.getConnecion();
		PreparedStatement pStatement = connection.prepareStatement(sql);
		if (null != param && param.length>0) {
			for(int i = 0; i < param.length; i++) {
				pStatement.setObject((i+1), param[i]);
			}
		}
		ResultSet rSet = pStatement.executeQuery();
		while(rSet.next()) {
			Object object = rowMapper.getObjectMapper(rSet);
			list.add(object);
		}
		close(rSet, pStatement);
		return list;
		
	}
	
	
	
	
	private static void close(ResultSet rSet, PreparedStatement pStatement) throws SQLException {
		if (null != rSet) {
			rSet.close();
		}
		if (null != pStatement) {
			pStatement.close();
		}
	}
}
